package options.controller;

import exceptions.SaveErrorException;
import java.awt.Component;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import options.view.OptionsWindow;
import view.OptionPanelInterface;

public class OptionsWindowListener {
	private OptionsWindow optionsWindow = null;
	
	public OptionsWindowListener(OptionsWindow optionsWindow) {
		this.optionsWindow = optionsWindow;
		this.optionsWindow.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		
		this.optionsWindow.addWindowListener(new WindowAdapter(){
			
			public void windowClosing(WindowEvent windEvn){
				OptionsWindowListener.this.onClose();
			}; 
		});
	}
	
	private void onModified(Component [] tabs){
		int choose = JOptionPane.showConfirmDialog(null, "Salvare le modifiche?", null, JOptionPane.YES_NO_CANCEL_OPTION);
		switch(choose) {
			case JOptionPane.YES_OPTION:
				for (int i = 0; i < tabs.length; i++)
					if(((OptionPanelInterface) tabs[i]).isModified())
						try {
							((OptionPanelInterface) tabs[i]).save();
						} catch (SaveErrorException e) {
							e.printStackTrace();
						}
				
				this.optionsWindow.dispose();
				break;
			case JOptionPane.NO_OPTION: 
				this.optionsWindow.dispose();
				break;
			case JOptionPane.CANCEL_OPTION : case JOptionPane.CLOSED_OPTION: 
				break;
		}
	}	
	
	private void onClose(){
		boolean modified = false;
		Component [] tabs = this.optionsWindow.getJTabbedPane().getComponents();
		for (int i = 0; i < tabs.length; i++) {
			if(((OptionPanelInterface) tabs[i]).isModified()){
				modified = true; 
				break;
			}
		}
		
		if(modified) {
			onModified(tabs);
		} else
			this.optionsWindow.dispose();
	}
}
